package com.indi.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.indi.common.to.es.SkuEsModelTO;
import com.indi.gulimall.search.constant.EsConstant;
import com.indi.gulimall.search.config.ElasticsearchConfig;
import com.indi.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {
    @Resource
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuEsModelTO> skuEsModelTOs) throws IOException {
        // 具体实现

        // 2. es批量保存这些数据
        // 创建批量保存请求 BulkRequest bulkRequest
        BulkRequest bulkRequest = new BulkRequest();

        // 遍历skuEsModels
        for (SkuEsModelTO skuEsModelTO : skuEsModelTOs) {
            // 创建索引请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);

            // 指定索引id
            indexRequest.id(skuEsModelTO.getSkuId().toString());

            // 设置Json索引数据
            String jsonData = JSON.toJSONString(skuEsModelTO);
            indexRequest.source(jsonData, XContentType.JSON);

            // 为批量保存请求添加单个保存请求，bulkRequest.add(Json索引数据)
            bulkRequest.add(indexRequest);
        }


        // 调用es远程连接，执行批量保存请求，返回BulkResponse
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, ElasticsearchConfig.COMMON_OPTIONS);

        // 获取是否保存成功bulkResponse.hasFailures()，定义为flag
        boolean hasFailures = bulkResponse.hasFailures();

        // stream 流：bulkResponse.getItems()
        // 映射：BulkItemResponse::getId
        // 收集：List<String> items
        List<String> items = Arrays.stream(bulkResponse.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
        // 打印 items
        log.info("成功保存：{}",items);
        // 返回 flag
        return hasFailures;
    }
}
